<template>
  <div class="products-container">
    <div class="header">
      <div class="header-left">
        <h2>商品浏览</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="openBatchOrderDialog" :disabled="selectedProducts.length === 0" style="margin-right: 10px">
          批量下单 ({{ selectedProducts.length }})
        </el-button>
        <el-button type="primary" @click="openOrderHistoryDialog">查看订单</el-button>
      </div>
    </div>

    <div class="filters">
      <el-input
        v-model="localSearchQuery"
        placeholder="搜索商品..."
        class="search-input"
        clearable
        @input="handleSearch"
        @clear="handleSearchClear"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="selectedCategory" placeholder="选择分类" class="category-select" @change="handleCategoryChange">
        <el-option label="全部" value="" />
        <el-option label="新鲜水果" value="新鲜水果类别" />
        <el-option label="绿色蔬菜" value="绿色蔬菜类别" />
        <el-option label="优质肉类" value="优质肉类类别" />
        <el-option label="新鲜海鲜" value="新鲜海鲜类别" />
      </el-select>
    </div>
    
    <el-empty v-if="loading" description="加载中...">
      <el-icon class="is-loading"><Loading /></el-icon>
    </el-empty>

    <el-alert
      v-else-if="error"
      :title="error"
      type="error"
      show-icon
    />

    <div v-else-if="filteredProducts.length === 0" class="no-products">
      <el-empty description="没有找到匹配的商品" />
    </div>

    <div v-else class="products-list">
      <el-table 
        :data="paginatedProducts" 
        style="width: 100%" 
        border 
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <!-- 添加商品图片列 -->
        <el-table-column label="商品图片" width="100">
          <template #default="{row}">
            <div class="product-image-container">
              <el-image 
                :src="getImageUrl(row.image_url)" 
                fit="cover"
                :preview-src-list="[getImageUrl(row.image_url)]"
                class="product-image"
                :initial-index="0"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" min-width="120" />
        <el-table-column label="商品类别" min-width="100">
          <template #default="{row}">
            <el-tag :type="getCategoryType(row.category)">
              {{ row.category }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="单价" min-width="100">
          <template #default="{row}">
            <span class="price">¥{{ row.price }}/{{ row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="supplier" label="供应商" min-width="120" />
        <el-table-column prop="description" label="商品描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{row}">
            <el-button type="primary" size="small" :disabled="row.stock <= 0" @click="openOrderDialog(row)">立即下单</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="filteredProducts.length"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 订单弹窗 -->
    <el-dialog
      v-model="orderDialogVisible"
      title="填写订单信息"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form :model="orderForm" label-width="100px" :rules="orderRules" ref="orderFormRef">
        <!-- 客户信息 -->
        <el-divider>客户信息</el-divider>
        <el-form-item label="收货地址" prop="address">
          <div class="address-input-group">
            <el-select v-model="orderForm.district" placeholder="请选择区域" class="district-select">
              <el-option
                v-for="district in beijingDistricts"
                :key="district"
                :label="district"
                :value="district"
              />
            </el-select>
            <el-input 
              v-model="orderForm.detailAddress" 
              placeholder="请输入详细地址，如：中关村街道 科技园1号楼（空格隔开）"
              @input="updateFullAddress"
              class="detail-address-input"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="orderForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="orderForm.remark" type="textarea" placeholder="请输入备注信息（可选）"></el-input>
        </el-form-item>
        
        <!-- 商品信息 -->
        <el-divider>商品信息</el-divider>
        <div v-for="(item, index) in orderForm.items" :key="index" class="order-item">
          <!-- 添加商品图片 -->
          <div class="order-item-image">
            <el-image 
              :src="getImageUrl(item.image_url)" 
              fit="cover"
              class="product-image-small"
            >
              <template #error>
                <div class="image-error-small">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
          
          <!-- 商品名称和单价 -->
          <div class="order-item-row">
            <el-form-item label="商品名称" class="order-form-item">
              <el-input v-model="item.product_name" disabled></el-input>
            </el-form-item>
            
            <el-form-item label="单价" class="order-form-item">
              <el-input v-model="item.unit_price" disabled>
                <template #append>{{ item.unit }}</template>
              </el-input>
            </el-form-item>
          </div>
          
          <!-- 数量和小计 -->
          <div class="order-item-row">
            <el-form-item label="数量" :prop="`items.${index}.quantity`" :rules="[{ required: true, message: '请输入数量', trigger: 'blur' }, { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }]" class="order-form-item">
              <el-input-number 
                v-model="item.quantity" 
                :min="1" 
                :max="item.max_quantity" 
                @change="calculateItemTotal(index)"
                @input="handleQuantityInput($event, index, item)"
              ></el-input-number>
            </el-form-item>
            
            <el-form-item label="小计" class="order-form-item">
              <el-input v-model="item.total_price" disabled>
                <template #prepend>¥</template>
              </el-input>
            </el-form-item>
          </div>
        </div>
        
        <!-- 订单总计 -->
        <el-divider>订单总计</el-divider>
        <div class="order-total">
          <span class="total-label">总金额：</span>
          <span class="total-amount">¥{{ calculateOrderTotal() }}</span>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder" :loading="submitting">确定下单</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量下单弹窗 -->
    <el-dialog
      v-model="batchOrderDialogVisible"
      title="批量下单"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-form :model="orderForm" label-width="100px" :rules="orderRules" ref="orderFormRef">
        <!-- 客户信息 -->
        <el-divider>客户信息</el-divider>
        <el-form-item label="收货地址" prop="address">
          <div class="address-input-group">
            <el-select v-model="orderForm.district" placeholder="请选择区域" class="district-select">
              <el-option
                v-for="district in beijingDistricts"
                :key="district"
                :label="district"
                :value="district"
              />
            </el-select>
            <el-input 
              v-model="orderForm.detailAddress" 
              placeholder="请输入详细地址，如：中关村街道 科技园1号楼（空格隔开）"
              @input="updateFullAddress"
              class="detail-address-input"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="orderForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="orderForm.remark" type="textarea" placeholder="请输入备注信息（可选）"></el-input>
        </el-form-item>
        
        <!-- 商品信息 -->
        <el-divider>商品信息</el-divider>
        <div v-for="(item, index) in orderForm.items" :key="index" class="order-item">
          <!-- 添加商品图片 -->
          <div class="order-item-image">
            <el-image 
              :src="getImageUrl(item.image_url)" 
              fit="cover"
              class="product-image-small"
            >
              <template #error>
                <div class="image-error-small">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
          
          <!-- 商品名称和单价 -->
          <div class="order-item-header">
            <span class="item-name">{{ item.product_name }}</span>
            <el-button 
              type="danger" 
              size="small" 
              icon="Delete" 
              circle 
              @click="removeOrderItem(index)"
              v-if="orderForm.items.length > 1"
            ></el-button>
          </div>
          <div class="order-item-row">
            <el-form-item label="单价" class="order-form-item">
              <el-input v-model="item.unit_price" disabled>
                <template #append>{{ item.unit }}</template>
              </el-input>
            </el-form-item>
            
            <el-form-item 
              label="数量" 
              :prop="`items.${index}.quantity`" 
              :rules="[
                { required: true, message: '请输入数量', trigger: 'blur' }, 
                { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
              ]" 
              class="order-form-item"
            >
              <el-input-number 
                v-model="item.quantity" 
                :min="1" 
                :max="item.max_quantity" 
                @change="calculateItemTotal(index)"
                @input="handleQuantityInput($event, index, item)"
              ></el-input-number>
            </el-form-item>
            
            <el-form-item label="小计" class="order-form-item">
              <el-input v-model="item.total_price" disabled>
                <template #prepend>¥</template>
              </el-input>
            </el-form-item>
          </div>
        </div>
        
        <!-- 订单总计 -->
        <el-divider>订单总计</el-divider>
        <div class="order-total">
          <span class="total-label">总金额：</span>
          <span class="total-amount">¥{{ calculateOrderTotal() }}</span>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchOrderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitOrder" :loading="submitting">确定下单</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 订单历史弹窗 -->
    <el-dialog
      v-model="orderHistoryDialogVisible"
      title="我的订单历史"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="order-history-filters">
        <el-form :inline="true" :model="orderHistoryForm">
          <el-form-item label="订单编号">
            <el-input v-model="orderHistoryForm.order_number" placeholder="请输入订单编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select 
              v-model="orderHistoryForm.status" 
              placeholder="选择状态" 
              clearable
              class="status-select"
            >
              <el-option label="全部" value="" />
              <el-option label="已付款" value="paid" />
              <el-option label="已发货" value="shipped" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="orderHistoryForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchOrderHistory">查询</el-button>
            <el-button @click="resetOrderHistoryForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-empty v-if="orderHistoryLoading" description="加载中...">
        <el-icon class="is-loading"><Loading /></el-icon>
      </el-empty>

      <el-alert
        v-else-if="orderHistoryError"
        :title="orderHistoryError"
        type="error"
        show-icon
      />

      <div v-else-if="orders.length === 0" class="no-orders">
        <el-empty description="暂无订单记录" />
      </div>

      <div v-else class="order-history-list">
        <el-collapse v-model="activeOrders">
          <el-collapse-item v-for="order in orders" :key="order.id" :name="order.id">
            <template #title>
              <div class="order-header">
                <span class="order-number">订单号: {{ order.order_number }}</span>
                <span class="order-date">下单时间: {{ formatDateTime(order.payment_time) }}</span>
                <el-tag :type="getOrderStatusType(order.status)">{{ getOrderStatusText(order.status) }}</el-tag>
                <span class="order-total">总金额: ¥{{ order.total_amount }}</span>
                <el-button 
                  v-if="order.status === 'paid' && !order.delivery_task"
                  type="danger" 
                  size="small" 
                  @click.stop="handleCancelOrder(order.id)"
                >
                  取消订单
                </el-button>
              </div>
            </template>
            
            <div class="order-detail">
              <div class="order-info">
                <p><strong>收货地址:</strong> {{ order.address }}</p>
                <p><strong>联系电话:</strong> {{ order.phone }}</p>
                <p v-if="order.remark"><strong>备注:</strong> {{ order.remark }}</p>
              </div>
              
              <el-table :data="order.items" border stripe>
                <el-table-column prop="product_name" label="商品名称" min-width="120"></el-table-column>
                <el-table-column label="单价" width="120">
                  <template #default="{row}">
                    <span class="price">¥{{ row.unit_price }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
                <el-table-column label="小计" width="120">
                  <template #default="{row}">
                    <span class="price">¥{{ (parseFloat(row.unit_price) * parseFloat(row.quantity)).toFixed(2) }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
        </el-collapse>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="orderHistoryForm.page"
            v-model:page-size="orderHistoryForm.limit"
            :total="orderTotal"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleOrderSizeChange"
            @current-change="handleOrderPageChange"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { Search, Loading, Picture } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { createOrder, getOrders, cancelOrder } from '@/api/order'

// 搜索和过滤
const localSearchQuery = ref('')
const selectedCategory = ref('')
const loading = ref(false)
const error = ref(null)
const products = ref([])
const allProducts = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 订单弹窗相关
const orderDialogVisible = ref(false)
const orderFormRef = ref(null)
const submitting = ref(false)

// 北京市区域数据
const beijingDistricts = ['北京市 朝阳区', '北京市 海淀区', '北京市 丰台区', '北京市 西城区', '北京市 东城区']
const selectedDistrict = ref('') // 选择的区域
const detailAddress = ref('') // 详细地址

// 批量下单相关
const batchOrderDialogVisible = ref(false)
const orderForm = reactive({
  address: '',
  district: '', // 新增：选择的区域
  detailAddress: '', // 新增：详细地址
  phone: '',
  remark: '',
  items: []
})

// 表单验证规则
const orderRules = {
  address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' },
    { min: 5, message: '地址长度至少5个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  'items.*.quantity': [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' },
    { 
      validator: (rule, value, callback, source, options) => {
        const index = parseInt(rule.field.match(/items\.(\d+)\.quantity/)[1])
        const item = orderForm.items[index]
        if (value > item.max_quantity) {
          callback(new Error(`库存不足，最大可购买数量为${item.max_quantity}${item.unit}`))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 订单历史相关
const orderHistoryDialogVisible = ref(false)
const orderHistoryLoading = ref(false)
const orderHistoryError = ref(null)
const allOrders = ref([]) // 存储所有订单
const orderTotal = ref(0)
const activeOrders = ref([])

// 订单状态选项
const orderStatusOptions = {
  'paid': '已付款',
  'shipped': '已发货',
  'completed': '已完成',
  'cancelled': '已取消'
}

// 订单历史表单
const orderHistoryForm = reactive({
  order_number: '',
  status: '',
  dateRange: [],
  page: 1,
  limit: 10
})

// 获取商品列表
const fetchProducts = async () => {
  loading.value = true
  error.value = null
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    console.log('开始获取商品列表')
    
    // 构建查询参数 - 不使用参数过滤，而是获取所有商品后在前端过滤
    const params = {}
    
    console.log('请求参数:', params)
    
    const response = await axios.get('/api/products/', {
      params,
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    console.log('获取商品列表响应:', response.data)
    
    if (response.data) {
      let productsData = []
      
      // 处理不同的响应数据结构
      if (Array.isArray(response.data)) {
        productsData = response.data
        total.value = response.data.length
      } else if (response.data.results && Array.isArray(response.data.results)) {
        productsData = response.data.results
        total.value = response.data.count || response.data.results.length
      } else if (response.data.items && Array.isArray(response.data.items)) {
        productsData = response.data.items
        total.value = response.data.total || response.data.items.length
      }
      
      // 处理并规范化每个商品的数据结构
      const normalizedProducts = productsData.map(product => {
        console.log('处理商品:', product)
        
        // 获取库存信息
        let stockQuantity = 0
        if (product.stock_info && Array.isArray(product.stock_info) && product.stock_info.length > 0) {
          // 确保转换为数字类型
          stockQuantity = parseInt(product.stock_info[0].current_stock, 10) || 0
          console.log(`商品 ${product.name} 的库存数量: ${stockQuantity}`)
        } else if (product.stock !== undefined) {
          stockQuantity = parseInt(product.stock, 10) || 0
        }
        
        // 如果库存为负数，设置为0
        stockQuantity = Math.max(0, stockQuantity)
        
        // 处理日期
        let expiryDate = product.expiry_date || product.expiryDate || null
        
        // 处理类别名称，去掉"类别"后缀
        let categoryName = ''
        let categoryId = null
        
        // 调试输出类别信息
        console.log('商品类别信息:', {
          category: product.category,
          category_id: product.category_id,
          category_detail: product.category_detail
        })
        
        if (product.category_detail) {
          categoryName = product.category_detail.description?.replace(/类别$/, '') || 
                        product.category_detail.name || '未分类'
          categoryId = product.category_detail.id
        } else if (product.category) {
          categoryName = typeof product.category === 'string' ? 
                        product.category.replace(/类别$/, '') : '未分类'
        }
        
        // 规范化商品数据
        return {
          id: product.id,
          name: product.name || '未命名商品',
          category: categoryName,
          categoryId: categoryId || product.category_id,
          price: Number(product.price) || 0,
          unit: product.unit || '个',
          supplier: product.supplier || '未知供应商',
          description: product.description || '无描述',
          stock: stockQuantity,
          expiryDate: expiryDate,
          image_url: product.image_url || product.image || '',
          // 保留原始数据，以防需要
          originalData: product
        }
      })
      
      // 保存所有产品数据
      allProducts.value = normalizedProducts
      
      // 根据选择的类别过滤产品
      filterProductsByCategory()
      
      console.log('处理后的商品列表:', products.value)
    } else {
      console.warn('商品列表响应格式不正确:', response)
      products.value = []
      allProducts.value = []
      total.value = 0
      throw new Error('未获取到商品数据')
    }
  } catch (err) {
    console.error('获取产品列表失败:', err)
    error.value = '获取产品列表失败: ' + (err.response?.data?.detail || err.message)
    ElMessage.error('获取产品列表失败: ' + (err.response?.data?.detail || err.message))
    products.value = []
    allProducts.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 按类别过滤产品
const filterProductsByCategory = () => {
  if (!selectedCategory.value) {
    // 如果没有选择类别，显示所有未过期的产品
    products.value = allProducts.value.filter(product => !isExpired(product));
    return;
  }
  
  const categoryName = selectedCategory.value.replace(/类别$/, '');
  console.log('过滤类别:', categoryName);
  
  // 根据类别名称过滤，并排除已过期商品
  products.value = allProducts.value.filter(product => {
    const categoryMatch = product.category === categoryName;
    const notExpired = !isExpired(product);
    console.log(`商品 ${product.name} 类别 ${product.category} 匹配 ${categoryName}: ${categoryMatch}, 未过期: ${notExpired}`);
    return categoryMatch && notExpired;
  });
  
  console.log(`过滤后的商品数量: ${products.value.length}`);
}

// 处理分类变化
const handleCategoryChange = () => {
  console.log('分类变更为:', selectedCategory.value)
  localSearchQuery.value = '' // 清空搜索
  filterProductsByCategory() // 直接过滤现有产品，无需重新获取
}

// 处理搜索
const handleSearch = () => {
  console.log('执行搜索，关键词:', localSearchQuery.value);
  
  // 如果搜索框为空，只按类别过滤
  if (!localSearchQuery.value) {
    filterProductsByCategory();
    return;
  }
  
  // 先获取当前类别过滤后的商品
  let filtered = [...allProducts.value].filter(product => !isExpired(product));
  
  // 如果选择了类别，先按类别过滤
  if (selectedCategory.value) {
    const categoryName = selectedCategory.value.replace(/类别$/, '');
    filtered = filtered.filter(product => product.category === categoryName);
  }
  
  // 搜索条件：转换为小写并去除首尾空格
  const query = localSearchQuery.value.toLowerCase().trim()
  
  // 安全地获取字符串值并转换为小写
  const safeToLowerCase = (value) => {
    if (typeof value === 'string') {
      return value.toLowerCase()
    }
    if (value === null || value === undefined) {
      return ''
    }
    return String(value).toLowerCase()
  }
  
  // 按搜索词过滤，支持多个字段的模糊匹配
  products.value = filtered.filter(product => {
    // 安全地获取所有需要搜索的字段值
    const name = safeToLowerCase(product.name)
    const description = safeToLowerCase(product.description)
    const supplier = safeToLowerCase(product.supplier)
    const category = safeToLowerCase(product.category)
    
    return name.includes(query) || 
           description.includes(query) || 
           supplier.includes(query) ||
           category.includes(query)
  })
}

// 处理搜索框清空
const handleSearchClear = () => {
  console.log('清空搜索')
  localSearchQuery.value = ''
  filterProductsByCategory() // 只按类别过滤
}

// 过滤商品列表
const filteredProducts = computed(() => {
  return products.value
})

// 分页后的商品列表
const paginatedProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredProducts.value.slice(start, end)
})

// 获取分类样式
const getCategoryType = (category) => {
  const types = {
    '绿色蔬菜': 'success',
    '新鲜水果': 'warning',
    '优质肉类': 'danger',
    '新鲜海鲜': 'info'
  }
  return types[category] || 'info'
}

const getStockStatusType = (stock) => {
  if (stock <= 0) return 'danger'
  if (stock < 100) return 'warning'
  return 'success'
}

const formatDate = (dateString) => {
  if (!dateString) return '未设置'
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return '日期无效'
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  } catch (error) {
    console.error('日期格式化错误:', error)
    return '日期错误'
  }
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  // 不再调用fetchProducts()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  // 不再调用fetchProducts()
}

// 打开订单弹窗
const openOrderDialog = (product) => {
  // 重置表单
  orderForm.address = ''
  orderForm.district = ''
  orderForm.detailAddress = ''
  orderForm.phone = ''
  orderForm.remark = ''
  orderForm.items = [{
    product_id: parseInt(product.id),
    product_name: product.name,
    quantity: 1,
    unit_price: parseFloat(product.price),  // 不要调用 toFixed，保持原始精度
    unit: product.unit,
    max_quantity: parseInt(product.stock),
    warehouse_id: parseInt(product.originalData.stock_info?.[0]?.warehouse_id || 1),
    total_price: parseFloat(product.price)  // 不要调用 toFixed，保持原始精度
  }]
  
  // 显示弹窗
  orderDialogVisible.value = true
}

// 计算商品小计
const calculateItemTotal = (index) => {
  const item = orderForm.items[index]
  
  // 确保数量不超过库存
  if (item.quantity > item.max_quantity) {
    ElMessage.warning({
      message: `商品"${item.product_name}"库存不足，最大可购买数量为${item.max_quantity}${item.unit}`,
      duration: 3000
    })
    item.quantity = item.max_quantity
  }
  
  // 使用 parseFloat 确保数字计算准确
  const quantity = parseFloat(item.quantity)
  const unitPrice = parseFloat(item.unit_price)
  item.total_price = quantity * unitPrice  // 不要调用 toFixed，保持原始精度
}

// 计算订单总金额
const calculateOrderTotal = () => {
  let total = 0
  orderForm.items.forEach(item => {
    total += parseFloat(item.total_price)
  })
  return total.toFixed(2)  // 只在显示时格式化为两位小数
}

// 提交订单
const submitOrder = async () => {
  // 表单验证
  if (!orderFormRef.value) return
  
  await orderFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请完善订单信息')
      return
    }
    
    // 验证地址是否完整
    if (!orderForm.district || !orderForm.detailAddress) {
      ElMessage.warning('请选择区域并填写详细地址')
      return
    }
    
    // 更新完整地址
    updateFullAddress()
    
    // 准备提交数据，严格按照API文档格式
    const submitData = {
      address: orderForm.address,
      phone: orderForm.phone,
      remark: orderForm.remark || '',
      items: orderForm.items.map(item => {
        // 确保所有数值都是数字类型
        const quantity = Number(item.quantity)
        const unitPrice = Number(item.unit_price)
        
        // 验证数量是否为正数
        if (isNaN(quantity) || quantity <= 0) {
          throw new Error(`商品"${item.product_name}"的数量必须大于0`)
        }
        
        // 验证单价是否为正数
        if (isNaN(unitPrice) || unitPrice <= 0) {
          throw new Error(`商品"${item.product_name}"的单价必须大于0`)
        }
        
        return {
          product_id: Number(item.product_id),
          quantity: quantity,
          unit_price: unitPrice
        }
      })
    }
    
    // 验证是否有商品项
    if (!submitData.items || submitData.items.length === 0) {
      ElMessage.error('订单必须包含至少一个商品')
      return
    }
    
    // 打印完整的请求数据
    console.log('准备提交的订单数据:', JSON.stringify(submitData, null, 2))
    
    submitting.value = true
    
    try {
      const response = await createOrder(submitData)
      console.log('订单提交响应:', response)
      
      if (response.code === 200) {
        ElMessage.success({
          message: '下单成功！订单号：' + response.data.order_number,
          duration: 5000
        })
        
        // 关闭对应的弹窗
        orderDialogVisible.value = false
        batchOrderDialogVisible.value = false
        
        // 清空选中的商品
        selectedProducts.value = []
        
        // 刷新商品列表
        await fetchProducts()
        
        // 如果订单历史弹窗是打开的，刷新订单历史
        if (orderHistoryDialogVisible.value) {
          await fetchOrderHistory()
        }
      } else {
        throw new Error('下单失败：' + (response.message || '未知错误'))
      }
    } catch (error) {
      console.error('下单失败:', error)
      // 打印更详细的错误信息
      if (error.response) {
        console.error('错误响应数据:', error.response.data)
        console.error('错误状态码:', error.response.status)
      }
      ElMessage.error({
        message: '下单失败: ' + (error.response?.data?.detail || error.response?.data?.message || error.message),
        duration: 5000
      })
    } finally {
      submitting.value = false
    }
  })
}

// 获取订单历史数据
const fetchOrderHistory = async () => {
  orderHistoryLoading.value = true
  orderHistoryError.value = null
  
  try {
    // 构建查询参数
    const params = {}
    
    if (orderHistoryForm.order_number) {
      params.order_number = orderHistoryForm.order_number
    }
    
    if (orderHistoryForm.status) {
      params.status = orderHistoryForm.status
    }
    
    if (orderHistoryForm.dateRange && orderHistoryForm.dateRange.length === 2) {
      params.start_date = orderHistoryForm.dateRange[0]
      params.end_date = orderHistoryForm.dateRange[1]
    }
    
    console.log('获取订单历史，参数:', params)
    
    const response = await getOrders(params)
    console.log('订单历史响应:', response)
    
    if (response.code === 200) {
      const responseData = response.data
      
      // 处理订单数据
      if (responseData) {
        if (responseData.items && Array.isArray(responseData.items)) {
          allOrders.value = responseData.items
          orderTotal.value = responseData.items.length
        } else if (responseData.results && Array.isArray(responseData.results)) {
          allOrders.value = responseData.results
          orderTotal.value = responseData.results.length
        } else if (Array.isArray(responseData)) {
          allOrders.value = responseData
          orderTotal.value = responseData.length
        } else {
          allOrders.value = []
          orderTotal.value = 0
        }
      } else {
        allOrders.value = []
        orderTotal.value = 0
      }
      
      // 如果没有订单，显示提示
      if (allOrders.value.length === 0) {
        console.log('未找到订单记录')
      } else {
        console.log(`获取到 ${allOrders.value.length} 条订单记录`)
      }
    } else {
      allOrders.value = []
      orderTotal.value = 0
      throw new Error('未获取到订单数据')
    }
  } catch (err) {
    console.error('获取订单历史失败:', err)
    orderHistoryError.value = '获取订单历史失败: ' + (err.response?.data?.detail || err.message)
    allOrders.value = []
    orderTotal.value = 0
  } finally {
    orderHistoryLoading.value = false
  }
}

// 取消订单
const handleCancelOrder = async (orderId) => {
  try {
    // 添加确认弹窗
    await ElMessageBox.confirm(
      '确定要取消该订单吗？取消后无法恢复。',
      '取消订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await cancelOrder(orderId)
    if (response.code === 200) {
      ElMessage.success('订单已取消')
      // 刷新订单列表
      fetchOrderHistory()
    } else {
      throw new Error(response.message || '取消订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') { // 用户点击取消按钮时不显示错误提示
      console.error('取消订单失败:', error)
      let errorMsg = '取消订单失败'
      
      // 处理后端返回的具体错误信息
      if (error.response?.data?.message) {
        errorMsg = error.response.data.message
      } else if (error.response?.data?.detail) {
        errorMsg = error.response.data.detail
      } else if (error.message) {
        errorMsg = error.message
      }
      
      ElMessage.error(errorMsg)
    }
  }
}

// 批量下单相关
const selectedProducts = ref([])
const handleSelectionChange = (selection) => {
  selectedProducts.value = selection.map(item => item.id)
}

const openBatchOrderDialog = () => {
  // 重置表单
  orderForm.address = ''
  orderForm.district = ''
  orderForm.detailAddress = ''
  orderForm.phone = ''
  orderForm.remark = ''
  
  // 获取选中的商品信息
  const selectedItems = paginatedProducts.value.filter(product => 
    selectedProducts.value.includes(product.id)
  ).map(product => ({
    product_id: parseInt(product.id),
    product_name: product.name,
    quantity: 1,
    unit_price: parseFloat(product.price),  // 不要调用 toFixed，保持原始精度
    unit: product.unit,
    max_quantity: parseInt(product.stock),
    warehouse_id: parseInt(product.originalData.stock_info?.[0]?.warehouse_id || 1),
    total_price: parseFloat(product.price)  // 不要调用 toFixed，保持原始精度
  }))
  
  orderForm.items = selectedItems
  
  // 显示弹窗
  batchOrderDialogVisible.value = true
}

const removeOrderItem = (index) => {
  orderForm.items.splice(index, 1)
  if (orderForm.items.length === 0) {
    batchOrderDialogVisible.value = false
  }
}

// 打开订单历史弹窗
const openOrderHistoryDialog = () => {
  orderHistoryDialogVisible.value = true
  resetOrderHistoryForm()
  fetchOrderHistory()
}

// 重置订单历史查询表单
const resetOrderHistoryForm = () => {
  orderHistoryForm.order_number = ''
  orderHistoryForm.status = ''
  orderHistoryForm.dateRange = []
  orderHistoryForm.page = 1
}

// 处理订单分页大小变化
const handleOrderSizeChange = (val) => {
  orderHistoryForm.limit = val
  orderHistoryForm.page = 1 // 重置到第一页
}

// 处理订单页码变化
const handleOrderPageChange = (val) => {
  orderHistoryForm.page = val
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  const types = {
    'pending': 'warning',
    'paid': 'success',
    'shipped': 'info',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return types[status] || 'info'
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  return orderStatusOptions[status] || '未知状态'
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '未设置'
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return '日期无效'
    
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    console.error('日期格式化错误:', error)
    return '日期错误'
  }
}

// 分页后的订单列表
const orders = computed(() => {
  const start = (orderHistoryForm.page - 1) * orderHistoryForm.limit
  const end = start + orderHistoryForm.limit
  return allOrders.value.slice(start, end)
})

// 判断商品是否过期
const isExpired = (product) => {
  if (!product.expiryDate) return false;
  try {
    const today = new Date();
    const expiryDate = new Date(product.expiryDate);
    if (isNaN(expiryDate.getTime())) return false;
    return expiryDate <= today;
  } catch (error) {
    console.error('过期判断错误:', error);
    return false;
  }
}

// 获取商品图片URL
const getImageUrl = (imageUrl) => {
  if (!imageUrl) {
    return 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'; // 保留默认图片
  }
  
  // 如果是完整URL，直接返回
  if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
    return imageUrl;
  }
  
  // 如果是相对路径，拼接后端地址
  // 使用环境变量中的API基础URL
  const baseUrl = import.meta.env.VITE_API_BASE_URL || import.meta.env.VITE_APP_BASE_API || 'http://localhost:8000';
  return `${baseUrl}/media/${imageUrl}`;
}

// 在 script setup 部分添加处理函数
const handleQuantityInput = (value, index, item) => {
  if (value > item.max_quantity) {
    ElMessageBox.alert(
      `该商品库存不足，最大可购买数量为${item.max_quantity}${item.unit}`,
      '库存提示',
      {
        confirmButtonText: '确定',
        type: 'warning'
      }
    )
    // 自动将数量设置为最大可购买数量
    item.quantity = item.max_quantity
    // 重新计算小计
    calculateItemTotal(index)
  }
}

// 添加更新完整地址的函数
const updateFullAddress = () => {
  if (orderForm.district && orderForm.detailAddress) {
    orderForm.address = `${orderForm.district} ${orderForm.detailAddress}`
  } else {
    orderForm.address = ''
  }
}

onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.products-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin-bottom: 20px;
  color: #303133;
}

.filters {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.category-select {
  width: 150px;
}

.products-list {
  margin-top: 20px;
}

.price {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.no-products {
  margin-top: 40px;
  text-align: center;
}

/* 批量下单样式 */
.order-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.item-name {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.order-item-row {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.order-form-item {
  flex: 1;
  margin-bottom: 0;
}

.header-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 修改订单弹窗样式 */
.order-item {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9f9f9;
  position: relative;
}

.order-total {
  text-align: right;
  margin: 20px 0;
  font-size: 16px;
}

.total-label {
  margin-right: 10px;
  font-weight: bold;
}

.total-amount {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 订单历史样式 */
.order-history-filters {
  margin-bottom: 20px;
  padding: 0 20px;
}

.order-header {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.order-number {
  font-weight: bold;
  color: #409EFF;
  min-width: 180px;
}

.order-date {
  color: #606266;
  min-width: 200px;
}

.order-total {
  font-weight: bold;
  color: #f56c6c;
  margin-left: auto;
}

.order-detail {
  margin-top: 15px;
  padding: 0 20px;
}

.order-info {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  max-width: calc(100% - 20px);
}

.order-info p {
  margin: 5px 0;
  word-break: break-all;
}

.no-orders {
  margin: 40px 0;
  text-align: center;
}

/* 修改el-collapse样式 */
:deep(.el-collapse) {
  padding: 0 20px;
}

:deep(.el-collapse-item__header) {
  padding: 12px;
  background-color: #f9f9f9;
}

:deep(.el-collapse-item__content) {
  padding: 15px 0;
}

/* 确保表格不会超出容器 */
:deep(.el-table) {
  width: 100% !important;
  max-width: 100%;
}

.status-select {
  width: 150px;
}

/* 添加样式 */
.address-input-group {
  display: flex;
  gap: 10px;
}

.district-select {
  width: 150px;
  flex-shrink: 0;
}

.detail-address-input {
  flex-grow: 1;
}

/* 商品图片样式 */
.product-image-container {
  width: 80px;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  margin: 0 auto;
}

.product-image {
  width: 100%;
  height: 100%;
  border-radius: 4px;
  object-fit: cover;
  transition: transform 0.3s;
  cursor: pointer;
}

.product-image:hover {
  transform: scale(1.05);
}

.product-image-small {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.order-item-image {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.image-error-small {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60px;
  height: 60px;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 18px;
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
}
</style>
